package com.stu.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.stu.commons.Result;
import com.stu.commons.ResultCode;
import com.stu.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Slf4j
@Component
public class JwtAuthInterceptor implements HandlerInterceptor {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 放行预检请求和公开API
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }

        String requestUri = request.getRequestURI();
        if (isPublicEndpoint(requestUri)) {
            return true;
        }

        // 2. 获取并验证Token
        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            sendErrorResponse(response, Result.fail(ResultCode.UNAUTHORIZED, "请携带有效的Token"));
            return false;
        }

        try {
            // 3. 解析JWT
//            System.out.println(token);

            String realToken = token.substring(7);
//            System.out.println(realToken);

//            Claims claims = JwtUtil.parseToken(realToken);
//            System.out.println(JwtUtil.getUserIdFromToken(realToken));

            Integer userId = Integer.valueOf(JwtUtil.getUserIdFromToken(realToken));
//            System.out.println(userId);
            // 4. 将用户信息存入请求属性（供Controller使用）
//            request.setAttribute("userId", claims.getSubject());
            request.setAttribute("userId", userId);
//            System.out.println("111"+request.getHeader("userId"));
            return true;
        } catch (Exception e) {
            log.error("Token验证失败: {}", e.getMessage());
            sendErrorResponse(response, Result.fail(ResultCode.FORBIDDEN, "Token已过期或无效"));
            return false;
        }
    }

    /**
     * 判断是否为公开接口
     */
    private boolean isPublicEndpoint(String uri) {
        return uri.startsWith("/pro/")  // 多余的判断条件,没进拦截器
                || uri.equals("/users/save")
                || uri.equals("/users/login");
//                || uri.equals("/api/auth/refresh-token");
    }

    /**
     * 统一JSON错误响应
     */
    private void sendErrorResponse(HttpServletResponse response, Result<?> result) throws Exception {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(result.getCode());
        try (PrintWriter writer = response.getWriter()) {
            writer.write(objectMapper.writeValueAsString(result));
            writer.flush();
        }
    }
}